<template>
  <div class="container_edit">
    <div class="header">
      <p>房源管理>>新增/编辑办公室</p>
      <el-button
        type="primary"
        @click="back"
      >返回</el-button>
    </div>
    <div class="main" style="overflow-x: scroll">
      <el-form
        :model="params"
        :rules="rules"
        ref="user"
        label-width="150px"
        class=""
      >
        <el-form-item
          label="图片："
          prop="imageKey"
        >
          <el-upload
            list-type="picture-card"
            class="normal-uploader"
            :http-request="http"
            action=''
            :limit='9'
            multiple
            :file-list='fileList'
            :on-remove="handleImageRemove"
            :before-upload="beforeAvatarUpload"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="写字楼名称："
          prop="buildingId"
        >
          <el-select v-model="params.buildingId" placeholder="请选择">
            <el-option
              v-for="item in buildingList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <div class="flex-box-align">
          <el-form-item
            label="办公室名称"
            prop="name"
          >
            <el-input
              v-model="params.name"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="空间"
            prop="degree"
          >
            <el-select v-model="params.degree" placeholder="请选择">
              <el-option
                v-for="item in degreeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="flex-box-align">
          <el-form-item
            label="单价"
            prop="unitPrice"
          >
            <el-input
              v-model="params.unitPrice"
              placeholder="请输入"
            ></el-input>元/m2
          </el-form-item>
          <el-form-item
            label="总价"
            prop="totalPrice"
          >
            <el-input
              v-model="params.totalPrice"
              placeholder="请输入"
            ></el-input>元/月
          </el-form-item>
        </div>
        <!--<el-form-item-->
          <!--label="简述"-->
          <!--prop="brief"-->
        <!--&gt;-->
          <!--<el-input-->
            <!--type="textarea"-->
            <!--:rows="3"-->
            <!--v-model="params.brief"-->
            <!--placeholder="请输入"-->
          <!--&gt;</el-input>-->
        <!--</el-form-item>-->
        <el-form-item
          label="标签"
          prop="tags"
        >
          <el-tag
            :key="tag"
            v-for="tag in params.tags"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)">
            {{tag}}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加标签</el-button>
        </el-form-item>
        <div class="sub_title">配套介绍</div>
        <el-form-item
          label="房号"
          prop="roomNo"
        >
          <el-input
            v-model="params.roomNo"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="面积"
          prop="area"
        >
          <el-input
            v-model="params.area"
            placeholder="请输入"
          ></el-input>m2
        </el-form-item>
        <el-form-item
          label="格局"
          prop="structure"
        >
          <el-input
            v-model="params.structure"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="朝向"
          prop="face"
        >
          <el-input
            v-model="params.face"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="工位"
          prop="seat"
        >
          <el-input
            v-model="params.seatMin"
            placeholder="请输入"
          ></el-input> ~
          <el-input
            v-model="params.seatMax"
            placeholder="请输入"
          ></el-input>个
        </el-form-item>
        <el-form-item
          label="装修情况"
          prop="decoration"
        >
          <el-input
            v-model="params.decoration"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="管理费"
          prop="managementFee"
        >
          <el-input
            v-model="params.managementFee"
            placeholder="请输入"
          ></el-input>元/m2
        </el-form-item>
        <el-form-item
          label="空调费"
          prop=""
        >
          <el-input
            v-model="params.airConditionerFee"
            placeholder="请输入"
          ></el-input>
          <!--元 /-->
          <!--<el-input-->
            <!--v-model="params.airConditionerUnit"-->
            <!--placeholder="请输入"-->
          <!--&gt;</el-input>-->
        </el-form-item>
        <el-form-item
          label="房源介绍"
          prop="introduce"
        >
          <bg-editor
            :minHeight="300"
            :uploadUrl="null"
            :content="params.introduce"
            @editorData='editorInfo'
          >
          </bg-editor>
        </el-form-item>
        <el-form-item
          label="房源视频"
          prop=""
        >
          <el-upload
            class="avatar-uploader"
            :action="upLoadUrl"
            :show-file-list="false"
            :before-upload="beforeVideoUpload"
          >
            <Video :src="videoUrl" controls v-if="videoUrl" style="width: 150px;"></Video>
            <i
              v-else
              class="el-icon-plus avatar-uploader-icon"
            ></i>
          </el-upload>
          <el-button icon="el-icon-delete" v-if="videoUrl" type="primary" size="mini" @click="handleDel">删除</el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="handleSave('user')"
          >保存</el-button>
          <el-button @click="back">返回</el-button>
        </el-form-item>
      </el-form>
    </div>

  </div>
</template>

<script>
  let CONSTANT = require("../../constant/constant.js");
  let common = require("../../common.js");
  var searchService,map,markers = [];
  export default {
    data() {
      return {
        upLoadUrl: "",
        imageUrl: "",
        videoUrl: "",
        params: {
          airConditionerFee: "",
          airConditionerUnit: "",
          area: "",
//          brief: "",
          buildingId: "",
          decoration: "",
          degree: "",
          face: "",
          imageKey: "",
          introduce: "",
          managementFee: "",
          name: "",
          roomNo: "",
          seatMax: "",
          seatMin: "",
          structure: "",
          tags: [],
          totalPrice: "",
          unitPrice: "",
          videoKey: "",
          id: "",
        },
        fileList: [],
        rules: {
          airConditionerFee: [
            { required: true, message: "请输入空调费", trigger: "blur" }
          ],
          area: [
            { required: true, message: "请输入面积", trigger: "blur" }
          ],
//          brief: [
//            { required: true, message: "请输入简述", trigger: "blur" }
//          ],
          buildingId: [
            { required: true, message: "请选择写字楼", trigger: "blur" }
          ],
          decoration: [
            { required: true, message: "请输入装修情况", trigger: "blur" }
          ],
          degree: [
            { required: true, message: "请选择空间", trigger: "blur" }
          ],
          face: [
            { required: true, message: "请输入朝向", trigger: "blur" }
          ],
          imageKey: [
            { required: true, message: "请上传图片", trigger: "blur" }
          ],
          introduce: [
            { required: true, message: "请输入房源介绍", trigger: "blur" }
          ],
          managementFee: [
            { required: true, message: "请输入管理费", trigger: "blur" }
          ],
          name: [
            { required: true, message: "请输入办公室名称", trigger: "blur" }
          ],
          roomNo: [
            { required: true, message: "请输入房号", trigger: "blur" }
          ],
          seatMax: [
            { required: true, message: "请输入最大工位", trigger: "blur" }
          ],
          seatMin: [
            { required: true, message: "请输入最小工位", trigger: "blur" }
          ],
          structure: [
            { required: true, message: "请输入格局", trigger: "blur" }
          ],
          tags: [
            { required: true, message: "请输入标签", trigger: "blur" }
          ],
          totalPrice: [
            { required: true, message: "请输入总价", trigger: "blur" }
          ],
          unitPrice: [
            { required: true, message: "请输入单价", trigger: "blur" }
          ],
        },
        inputVisible: false,
        inputValue: '',
        buildingList: [],
        degreeList: [{
          label: "经济",
          value: "ECONOMY"
        },{
          label: "舒适",
          value: "COMFORT"
        },{
          label: "高端",
          value: "HIGHEND"
        }],
        id: ""
      };
    },
    created() {
    },
    mounted() {
      this.id = this.$route.query.id;
      this.pageIndex = this.$router.currentRoute.query.pageIndex||1;
      let sessionId = sessionStorage.getItem("sessionId");
      this.upLoadUrl =
        CONSTANT.URL.SYSTEM.UPLOADFILEBYCOS + "?sessionId=" + sessionId;
      if (this.id) {
        this.getInfo();
      }
      this.getList()
    },
    components: {
      "bg-editor": () => import("../common/bg-editor.vue")
    },
    methods: {
      handleDel(){
        this.videoUrl = ''
        this.params.videoKey = ''
      },
      getInfo: function() {
        let url = CONSTANT.URL.ROOM.detail;
        common.get(url,this.id, res => {
          if (res.status == 200) {
            let data = res.data.bussData;
            this.params = data;
            this.videoUrl = data.videoUrl
            let arr = []
            data.tags.map( item => {
              arr.push(item.name)
            })
            this.params.tags = arr
            data.images.map( item => {
              this.fileList.push({
                url: item.fileUrl,
                fileKey: item.fileKey
              })
            })
          }
        });
      },
      getList() {
        let url = CONSTANT.URL.BUILDING.box;
        common.get(url,'', res => {
          if (res.status == 200) {
            let data = res.data.bussData;
            this.buildingList = data;
          }
        });
      },
      handleSave: function(formName) {
        this.params.imageKey = ""
        let arr = []
        this.fileList.map( item => {
          if (item.fileKey) {
            arr.push(item.fileKey)
          }
        })
        this.params.imageKey = arr.join(',')
        this.$refs[formName].validate(valid => {
          if (valid) {
            let url = CONSTANT.URL.ROOM.save;
            this.params.seatMax = this.params.seatMax ? this.params.seatMax : null
            this.params.seatMin = this.params.seatMin ? this.params.seatMin : null
            this.params.airConditionerUnit = this.params.airConditionerUnit ? this.params.airConditionerUnit : null
            this.params.airConditionerFee = this.params.airConditionerFee ? this.params.airConditionerFee : null
            common.requestAjax(url, JSON.stringify(this.params), '', res => {
              if (res.status == 200) {
                this.$message({
                  type: "success",
                  message: "保存成功！"
                });
                this.$router.replace('/roomList?pageIndex='+this.pageIndex)
              } else {
                this.$message({
                  type: "warning",
                  message: res.msg
                });
              }
            });
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      beforeAvatarUpload(file) {
        this.fileAdd(file)

      },
      urpChange(file){
        let url = CONSTANT.URL.SYSTEM.UPLOADFILEBYCOS;
        let param = {
          suffix:file.name?file.name.split(".")[1]:'jpeg', // 文件后缀  png
          contentType: file.type // 文件类型  image/png
        };
        common.requestAjax(url, '', param, res => {
          this.upLoadUrl = res.data.bussData.uploadUrl;
          console.log(this.params.imageKey)
          common.uploadFile(this.upLoadUrl, file, file.type, res1 => {
            this.fileList.push({
              url: res.data.bussData.downloadUrl,
              fileKey: res.data.bussData.fileKey,
            })
          })
        });
      },
      fileAdd(file) {
            //判断是否为图片文件
            if (file.type.indexOf('image') == -1) {
                this.$msgbox("请选择图片文件")
            } else {
                let reader = new FileReader();
                let image = new Image();
                let _this = this;
                reader.readAsDataURL(file);
                reader.onload = function () {
                    file.src = this.result;
                    image.onload = function(){
                        let width = image.width;
                        let height = image.height;
                        file.width = width;
                        file.height = height;
                        _this.imgL = file.src  //页面上显示所选择的图片
                    };

                    image.src= file.src; //页面上显示所选择的图片
                    if(file.size/1024 > 1025){  //判断图片的大小，超过1M 进行压缩
                        _this.imgCompress(file,{quality: 0.2})
                    }else{
                        _this.urpChange(file)
                        _this.partitionBase = file.src.split(",")[1]  //这里是因为后台需要 base64和图片type类型两个数据，所以进行了处理
                        _this.imgType ="."+file.type.split("/")[1]
                    }
                }
            }
      },
      //图片压缩
      imgCompress(path,obj){   //path是指上传的图片，obj是压缩的品质，越低越模糊
          let _this = this  //这里的this 是把vue的实例对象指向改变为_this 
          var img = new Image();
          img.src = path.src;
          img.onload = function(){
              var that = this;  //这里的this 是把img的对象指向改变为that 
              // 默认按比例压缩
              var w = that.width,
                  h = that.height,
                  scale = w / h;
              w = obj.width || w;
              h = obj.height || (w / scale);
              var quality = 0.7;  // 默认图片质量为0.7
              //生成canvas
              var canvas = document.createElement('canvas');
              var ctx = canvas.getContext('2d');
              // 创建属性节点
              var anw = document.createAttribute("width");
              anw.nodeValue = w;
              var anh = document.createAttribute("height");
              anh.nodeValue = h;
              canvas.setAttributeNode(anw);
              canvas.setAttributeNode(anh);
              ctx.drawImage(that, 0, 0, w, h);
              // 图像质量
              if(obj.quality && obj.quality <= 1 && obj.quality > 0){
                  quality = obj.quality;
              }
              // quality值越小，所绘制出的图像越模糊
              var base64 = canvas.toDataURL('image/jpeg', quality);
              // 回调函数返回base64的值
              var urlFile = _this.convertBase64UrlToBlob(base64)  //这个地方的处理是为了把压缩的base64转化为对象，获得压缩后图片的大小size，方便对压缩后的图片再次进行判断；
              console.log(urlFile,'urlFileurlFile')
              _this.urpChange(urlFile)
              if(urlFile.size/1024 > 1025){
                  _this.$msgbox("图片过大，请重新上传图片")
              }else{
                  _this.partitionBase = base64.split(",")[1]
                  _this.imgType ="."+urlFile.type.split("/")[1]
              }
          }
      },
      //将base64码转化为file（Blob）
      //此处函数对压缩后的base64经过处理返回{size: "", type: ""} 
      convertBase64UrlToBlob(urlData){
            var arr = urlData.split(','), mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
            while(n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], {type:mime});
      },
      handleImageRemove(file, fileList) {
        let list = []
        fileList.map((item, index) => {
          this.fileList.map((item1, index1) => {
            if (item.url == item1.url) {
              list.push(item1)
            }
          })
        })
        this.fileList = list
      },
      beforeVideoUpload(file) {
        let url = CONSTANT.URL.SYSTEM.UPLOADFILEBYCOS;
        let param = {
          suffix: file.name.split(".")[1], // 文件后缀  png
          contentType: file.type // 文件类型  image/png
        };
        common.requestAjax(url, '', param, res => {
          this.upLoadUrl = res.data.bussData.uploadUrl;
          this.params.videoKey = res.data.bussData.fileKey;
          common.uploadFile(this.upLoadUrl, file, file.type, res1 => {
            this.videoUrl = res.data.bussData.downloadUrl;
          })
        });
      },
      editorInfo(e) {
        this.params.introduce = e
        console.log(this.params.introduce)
      },
      back() {
       this.$router.replace('/roomList?pageIndex='+this.pageIndex)
      },
      handleClose(tag) {
        this.params.tags.splice(this.params.tags.indexOf(tag), 1);
      },

      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },

      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
          this.params.tags.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
      },
      http(){},
      init() {
        let self = this
        var center = new qq.maps.LatLng(39.916527,116.397128);
        map = new qq.maps.Map(document.getElementById('map_canvas'),{
          center: center,
          zoom: 13
        });
        var latlngBounds = new qq.maps.LatLngBounds();
        //调用Poi检索类
        searchService = new qq.maps.SearchService({
          pageIndex: 1,
          pageCapacity: 1,
          complete: function(results){
            self.params.latitude = results.detail.pois[0].latLng.lat
            self.params.longitude = results.detail.pois[0].latLng.lng
            console.log(results.detail)
            var pois = results.detail.pois;
            for(var i = 0,l = pois.length;i < l; i++){
              var poi = pois[i];
              latlngBounds.extend(poi.latLng);
              var marker = new qq.maps.Marker({
                map:map,
                position: poi.latLng
              });

              marker.setTitle(i+1);

              markers.push(marker);
            }
            map.fitBounds(latlngBounds);
          }
        });
      },
      clearOverlays(overlays){
        var overlay;
        while(overlay = overlays.pop()){
          overlay.setMap(null);
        }
      },
      searchKeyword(e) {
//        var keyword = document.getElementById("keyword").value;
//        var region = document.getElementById("region").value;
        this.clearOverlays(markers);
//        searchService.setLocation(region);
        searchService.search(this.params.detailAddress);
      }
    }
  };
</script>
<style lang="scss" scoped>
  #map_canvas {
    width:500px;
    height:500px;
  }
  .table-content {
    width: 500px;
    .table-item {
      position: relative;
      border: 1px solid #dcdfe6;
      i {
        position: absolute;
        right: -30px;
        top: 20px;
        cursor: pointer;
        font-size: 16px;
      }
      &:first-child {
        background-color: #409eff;
        color: #fff;
        border-right: 0px solid #dcdfe6;
        .table-list {
          padding: 0;
        }
      }

      .table-list {
        flex: 2;
        text-align: center;
        padding: 5px 0;
        .el-input {
          height: 70% !important;
          width: 90%;
        }
        &:first-child {
          flex: 3;
          border-right: 1px solid #dcdfe6;
        }
      }
    }
  }
</style>
